<?php

class stSocialMediaToolboxHook extends sthook_2_1 {

    public function  __construct($config) {
        parent::__construct($config);
        $this->config ['appDir'] = $this->config['pluginDir'] . 'applications/';
    }

    public function hookCustom() {
        $method = array($this, 'showstSocialMediaToolbox');
        add_shortcode('ShowstSocialMediaToolbox', $method);

        $method = array($this, 'loginRedirect');
        add_filter('login_redirect', $method, 50);
        $method = array($this, 'phpmailerInit');
        add_action('phpmailer_init', $method, 100, 1);
        $method = array($this, 'user_login');
        add_action('wp_login', $method);
        $method = array($this, 'user_login_failed');
        add_action('wp_login_failed', $method);
        $method = array($this, 'user_login_authenticate_failed');
        add_filter('authenticate', $method, 10, 3);
//        $method = arrary($this,'user_logoff');
//        add_action('wp logout', $method);
        $method = array($this, 'isNotAminRedirect');
       // add_action('admin_init', $method);

        $method = array($this, 'faviconLogo');
        add_filter('admin_head', $method, 100, 3);
        
        $method = array($this, 'logOutRedirect');
        add_filter('wp_logout', $method, 110);
         
        remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 ); // for the admin page  
        remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); // for the front end 
        $method = array($this, 'remove_admin_bar_style_backend');
        add_filter('admin_head', $method);
        
        $method = array($this, 'mediaLibraryHeadScript');
        add_action('admin_head_media_upload_library_form', $method);
        $method = array($this, 'addAttachment');
        add_action('add_attachment', $method, 100);
        $method = array($this, 'attachemntPostLimits');
        add_filter('post_limits', $method, 100);
    }
    
    function remove_admin_bar_style_backend() {  
      echo '<style>body.admin-bar #wpcontent, body.admin-bar #adminmenu { padding-top: 0px !important; }</style>';  
    } 
    
    function user_logoff(){
        echo 'hello world';
       
    }
    public function user_login($username){
       global $wpdb;
       $user = $this->getBrowser();
       $data['type'] = 'login';
       $data['type'] = 'login';
       $data['date'] = date_i18n('Y-m-d H:i:s');
       $data['username'] = $username;
       $data['browser'] = $user['name'].' '.$user['version'];
       $data['os'] = $user['platform'];
       $data['ip'] = $_SERVER['REMOTE_ADDR'];
       $wpdb->insert('wp_st_user_log',$data);
    }
    public function user_login_authenticate_failed($user, $username, $password){
        if(empty($password) && !empty($username)){
           global $wpdb;
           $user = $this->getBrowser();
           $data['type'] = 'login';
           $data['type'] = 'login';
           $data['date'] = date_i18n('Y-m-d H:i:s');
           $data['username'] = $username;
           $data['browser'] = $user['name'].' '.$user['version'];
           $data['os'] = $user['platform'];
           $data['ip'] = $_SERVER['REMOTE_ADDR'];
           $data['status'] = 0;
           $wpdb->insert('wp_st_user_log',$data);
        }
    }
    public function user_login_failed($username){
       global $wpdb;
       $user = $this->getBrowser();
       $data['type'] = 'login';
       $data['type'] = 'login';
       $data['date'] = date_i18n('Y-m-d H:i:s');
       $data['username'] = $username;
       $data['browser'] = $user['name'].' '.$user['version'];
       $data['os'] = $user['platform'];
       $data['ip'] = $_SERVER['REMOTE_ADDR'];
       $data['status'] = 0;
       $wpdb->insert('wp_st_user_log',$data);
    }
    public function getBrowser()
    {
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $bname = 'Unknown';
        $platform = 'Unknown';
        $version= "";

        //First get the platform?
        if (preg_match('/linux/i', $u_agent)) {
            $platform = 'Linux';
        }
        elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
            $platform = 'Mac';
        }
        elseif (preg_match('/windows|win32/i', $u_agent)) {
            $platform = 'Windows';
        }

        // Next get the name of the useragent yes seperately and for good reason
        if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
        {
            $bname = 'Internet Explorer';
            $ub = "MSIE";
        }
        elseif(preg_match('/Firefox/i',$u_agent))
        {
            $bname = 'Mozilla Firefox';
            $ub = "Firefox";
        }
        elseif(preg_match('/Chrome/i',$u_agent))
        {
            $bname = 'Google Chrome';
            $ub = "Chrome";
        }
        elseif(preg_match('/Safari/i',$u_agent))
        {
            $bname = 'Apple Safari';
            $ub = "Safari";
        }
        elseif(preg_match('/Opera/i',$u_agent))
        {
            $bname = 'Opera';
            $ub = "Opera";
        }
        elseif(preg_match('/Netscape/i',$u_agent))
        {
            $bname = 'Netscape';
            $ub = "Netscape";
        }

        // finally get the correct version number
        $known = array('Version', $ub, 'other');
        $pattern = '#(?<browser>' . join('|', $known) .
        ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
        if (!preg_match_all($pattern, $u_agent, $matches)) {
            // we have no matching number just continue
        }

        // see how many we have
        $i = count($matches['browser']);
        if ($i != 1) {
            //we will have two since we are not using 'other' argument yet
            //see if version is before or after the name
            if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
                $version= $matches['version'][0];
            }
            else {
                $version= $matches['version'][1];
            }
        }
        else {
            $version= $matches['version'][0];
        }

        // check if we have a number
        if ($version==null || $version=="") {$version="?";}

        return array(
            'userAgent' => $u_agent,
            'name'      => $bname,
            'version'   => $version,
            'platform'  => $platform,
            'pattern'    => $pattern
        );
    }

    public function includeExtraPlugin() {
        // default process here        
    }

    //Initialize hook function

    public function loginRedirect($redirect_to){
        global $current_user;
        //$user = get_userdata($current_user->ID);
        $redirect_to = admin_url("/?page={$this->config['plugin_name']}");
        return $redirect_to;
    }

    public function phpmailerInit($phpmailer){
        $option = $this->getFullOptions();
        $option = $option['settingEmail'];
        if ($option['isSmtp']) {
            $phpmailer->IsSMTP();
            $phpmailer->Host = $option['smtpHost'];
            $phpmailer->Port = $option['smtpPort'];
            $phpmailer->SMTPAuth = $option['smtpAuthentication'];
            $phpmailer->SMTPSecure = $option['smtpSsl'];
            $phpmailer->Username = $option['smtpUsername'];
            $phpmailer->Password = $option['smtpPassword'];
            $phpmailer->Body    = do_shortcode($phpmailer->Body);
            if(!empty($option['smtpFromemail']))
            $phpmailer->From     = $option['smtpFromemail'];
            if(!empty($option['smtpFromname']))
            $phpmailer->FromName = $option['smtpFromname'];
        }else{
            if(!empty($option['smtpFromemail']))
            $phpmailer->From     = $option['smtpFromemail'];
            if(!empty($option['smtpFromname']))
            $phpmailer->FromName = $option['smtpFromname'];
        }
    }

    public function showToolBar($args) {
        $controllerName = $this->config['plugin_name'] . "Controller";
        $controllerObject = new $controllerName($this->config);
        if($this->option['toolIsShow'])
            echo $controllerObject->getAction('showToolBar', $args);
    }

    public function isNotAminRedirect($args) {
        $user = get_current_user_id();
        if(!user_can($user, 'edit_dashboard') && empty($_REQUEST['page'])){
            wp_redirect(admin_url('/admin.php?page='.$this->config['plugin_name']));
        }
    }

    public function faviconLogo(){
        $this->config ['imagesUrl'] = WP_PLUGIN_URL . '/' . $this->config ['plugin_name'] . '/images/';
        echo "<link rel=\"shortcut icon\" type=\"image/vnd.microsoft.icon\" href=\"{$this->config ['imagesUrl']}smt_favicon.ico?m=1285358655g\" sizes=\"16x16 32x32 48x48\" />"
            ."<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"{$this->config ['imagesUrl']}smt_favicon.ico?m=1285358655g\" sizes=\"16x16\" />"
            ."<link rel=\"icon\" type=\"image/x-icon\" href=\"{$this->config ['imagesUrl']}smt_favicon.ico?m=1285358655g\" sizes=\"16x16\" />"
        ;
    }
    
    public function logOutRedirect(){
        
        wp_redirect(home_url('/admin'));
        die;
    }

    public function mediaLibraryHeadScript() {
        $userID = get_current_user_id();
        $user_meta_attachment = get_user_meta($userID, 'attachmentIDs', true);
        if (is_array($user_meta_attachment)) {
            
        } else {
            $data = array();
            $data[] = $user_meta_attachment;
            $user_meta_attachment = $data;
        }
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function() {
                var id1 = '';
                var id = '';
                var arr = [<?php echo implode(', ', $user_meta_attachment);?>];
                jQuery('#media-items .media-item').each(function(){
                    id1 = jQuery(this).attr('id');
                    id = id1.split('-');
                    id = id[2];
                    id = parseInt(id);
                    if (arr.join(" ").indexOf(id) < 0) {
                        jQuery('#'+id1).css('display', 'none');
                    }else{
                        //alert(id +" ok");
                    }
                });
            });
        </script>
        <?php
    }

    public function addAttachment($attachmentID) {
        $userID = get_current_user_id();
        $user_meta_attachment = get_user_meta($userID, 'attachmentIDs', true);
        if (is_array($user_meta_attachment)) {
            $user_meta_attachment[] = intval($attachmentID);
        } else {
            $data = array();
            $data[] = intval($user_meta_attachment);
            $data[] = intval($attachmentID);
            $user_meta_attachment = $data;
        }
        update_user_meta($userID, 'attachmentIDs', $user_meta_attachment);
    }
    
    public function attachemntPostLimits(){
        $start = ( $_GET['paged'] - 1 ) * 10;
	if ( $start < 1 )
		$start = 0;
        return "LIMIT $start, 10000";
    }
    
}

?>